package com.gjy.leetcode.eoa.chapter1;

import java.util.BitSet;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-03-16 08:59:43
 */
public class CompressGene {

    private BitSet bitSet;
    private int length;

    /*public CompressGene(String gene) {
        compress(gene);
    }*/

    public BitSet compress(String gene) {
        length = gene.length();
        bitSet = new BitSet(length * 2);
        String upper = gene.toUpperCase();

        for (int i = 0; i < length; i++) {
            int first = 2 * i;
            int second = 2 * i + 1;
            switch (upper.charAt(i)) {
                case 'A':
                    bitSet.set(first, false);
                    bitSet.set(second, false);
                    break;
                case 'C':
                    bitSet.set(first, false);
                    bitSet.set(second, true);
                    break;
                case 'G':
                    bitSet.set(first, true);
                    bitSet.set(second, false);
                    break;
                case 'T':
                    bitSet.set(first, true);
                    bitSet.set(second, true);
                    break;
                default:
                    throw new IllegalArgumentException();
            }
        }
        return bitSet;
    }

    public String decompress() {
        if (bitSet == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < (length * 2); i += 2) {
            int first = (bitSet.get(i) ? 1 : 0);
            int second = (bitSet.get(i + 1) ? 1 : 0);
            int last = first << 1 | second;
            switch (last) {
                case 0b00: // 00 A
                    sb.append('A');
                    break;
                case 0b01: // 00 A
                    sb.append('C');
                    break;
                case 0b10: // 00 A
                    sb.append('G');
                    break;
                case 0b11: // 00 A
                    sb.append('T');
                    break;
            }
        }
        return sb.toString();
    }

}
